﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using SqlSugar.Extensions;
using System.Data;
using System.Linq.Expressions;
using WebApi.Core.Common.HttpContextUser;
using WebApi.Core.IService;
using WebApi.Core.Model;
using WebApi.Core.Model.ResponseModels;
using WebApi.Core.Service;

namespace WebApi.Core.Api.Controllers
{
    [Authorize]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IUser _user;

        public UserController(IUserService userService, IUser user)
        {
            _userService = userService;
            _user = user;
        }
        
        [HttpGet]
        public async Task<ApiResponse<PageResult<Users>>> GetUsers(string? queryUser, bool? isActive, int pageIndex, int pageSize)
        {
            var res = await _userService.QueryUsersAsync(queryUser, isActive, pageIndex, pageSize);
            return ApiResponse<PageResult<Users>>.Success(res);
        }

        [HttpPost]
        public async Task<ApiResponse<string>> Add([FromBody] Users user)
        {
            user.Creator = _user.Name;
            user.CreateTime = DateTime.Now;
            var id = await _userService.InsertAsync(user); 
            return id > 0 ? ApiResponse<string>.Success(id.ObjToString(), "添加成功") : ApiResponse<string>.Fail("添加失败");
        }

        [HttpPut]
        public async Task<ApiResponse<string>> Update([FromBody] Users user)
        {
            if (user ==null || user.Id <= 0) 
                return ApiResponse<string>.Fail("缺少参数"); 

            user.Updater = _user.Name;
            user.UpdateTime = DateTime.Now;
            var sucess = await _userService.UpdateAsync(user);
            return await _userService.UpdateAsync(user) ? ApiResponse<string>.Success(user.Id.ObjToString(), "更新成功") : ApiResponse<string>.Fail("更新失败"); 
        }

        [HttpDelete]
        public async Task<ApiResponse<string>> Delete(int id)
        { 
            if (id <= 0) 
                return ApiResponse<string>.Fail("缺少参数");

            var user = await _userService.QueryById(id);
            if (user == null) 
                return ApiResponse<string>.Fail("用户不存在");

            user.IsDeleted = true; 
            user.Updater = _user.Name;
            user.UpdateTime = DateTime.Now;

            return await _userService.UpdateAsync(user) ? ApiResponse<string>.Success(user.Id.ObjToString(), "删除成功") : ApiResponse<string>.Fail("删除失败"); 

            //return await _userService.DeleteByIdAsync(id) ? ApiResponse<string>.Success(user.Id.ObjToString(), "更新成功") : ApiResponse<string>.Fail("更新失败");
        }
        
    }
}
